function start() {
	let username = document.getElementById('username').value;
	let password = document.getElementById('password').value;
	if (document.getElementById('remember').checked) {
		saveUserCredential(username, password);
	}
	login(username, password);
}

function registerWorker() {
	let username = document.getElementById('register-username');
	let password = document.getElementById('register-password');
	let confirm = document.getElementById('password-confirm');
	let btn = document.getElementById('register-button');
	let components = [username, password, confirm, btn];
	disableItems(components);
	if (password.value !== confirm.value) {
		toast('密码不一致');
		enableItems(components);
		return;
	}
	register(username.value, password.value);
	setTimeout(function () {
		enableItems(components);
	}, 1500);
}

function addPerson() {
	let uid = document.getElementById('add-person-uid').value;
	if (uid.length < 5) {
		return;
	}
	try {
		let parsedUid = Number(uid);
		modifyContacts(parsedUid, 0).finally(() => {
			closeDialog();
		});
	} catch (e) {
		toast('请输入有效 UID');
	}
}

function refreshContacts() {
	populateContacts();
}

function saveSettings() {
	setServer(document.getElementById('ip').value, document.getElementById('port').value, document.getElementById('secure').checked);
	toast('设置已保存');
	setTimeout(function () {
		goto('index', '登录');
	}, 1000);
}

function sendMessage() {
	let inputBox = document.getElementById('chatmsg');
	let content = inputBox.value;
	if (content.length >= 1 && parcel.currentUid > 0) {
		let obj = {
			time: Date.now(),
			data: {
				type: document.getElementById('isRawHtml').checked ? 4 : 0,
				content: content
			}
		};
		inputBox.value = '';
		writeMessage(parcel.currentUid, obj).then(result => {
			if (result) {
				dyalogAppend(parcel.currentUid, obj, true);
			}
		}).catch((e) => console.log(e));
	}
}

function saveInfo() {
	let username = document.getElementById('self-name').value;
	let isIntrovert = document.getElementById('self-introvert').checked;
	if (username.trim().length > 0) {
		modifyInfo(username, isIntrovert);
	}
}

function logout() {
	// XXX: shall logout gracefully
	closeDialog();
	location.reload();
}

function sendFile() {
	dyalogSelectFile().then(file => {
		let currentUid = parcel.currentUid;
		if (currentUid < 10000) {
			toast('收件人无效');
			return;
		}
		parcel.activeUploads['currentUid'] = file.name;
		let form = new FormData();
		form.append('file', file);
		let request = new XMLHttpRequest();
		request.onreadystatechange = () => {
			if (request.readyState === 4) {
				try {
					let result = JSON.parse(request.response);
					if (result.status === 0) {
						let obj = {
							time: Date.now(),
							data: {
								type: 7,
								encoding: `${file.name.split('.').pop()}`,
								data: `${file.name}\r\n${result.token}`
							}
						};
						writeMessage(parcel.currentUid, obj).then(result => {
							if (result) {
								dyalogAppend(parcel.currentUid, obj, true);
							}
						}).catch((e) => console.log(e));
					} else {
						toast('文件传输失败');
					}
				} catch (e) {
					toast('文件传输时遇到了意外错误');
					console.log(e);
				} finally {
					parcel.activeUploads[currentUid] = undefined;
					let uploadBox = document.getElementById('uploadbox');
					uploadBox.classList.add('hidden');
				}
			}
		};
		request.upload.onerror = (e) => {
			console.log(e);
			toast('上传文件时发生错误');
		};
		request.upload.onprogress = (e) => {
			// query is required since it might change
			if (parcel.currentUid === currentUid) {
				let percentageBox = document.getElementById("uploadPercentage");
				if (percentageBox) {
					if (e.lengthComputable) {
						let percentage = 100 * (e.loaded / e.total);
						percentageBox.innerText = `${percentage.toFixed(1)}%`;
					} else {
						percentageBox.innerText = '正在上传...';
					}
				}
			}
		};
		let server = getServer();
		request.open('POST', `${server.secure ? 'https' : 'http'}://${server.addr}:${server.port}/upload`);
		request.send(form);
	}).catch(() => {
		// no file selected
		toast('取消发送');
	});
}
